package com.omesoft.hksnore.user;

import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.omesoft.hksnore.MainActivity;
import com.omesoft.hksnore.R;
import com.omesoft.hksnore.util.CustomToast;
import com.omesoft.hksnore.util.dialog.MyProgressBarDialogUtil;
import com.omesoft.hksnore.util.json.ReErrorCode;
import com.omesoft.hksnore.util.json.SnorekillerJsonUtil;
import com.omesoft.hksnore.util.myactivity.MyActivity;
import com.omesoft.hksnore.util.titlebar.MyTitlebarUtil;
import com.omesoft.hksnore.util.web.CheckNetwork;
import com.omesoft.hksnore.util.web.DataCheckUtil;
import com.umeng.analytics.MobclickAgent;

/**
 * Created by Omesoft on 2017/2/17.
 */

public class LoginActivity extends MyActivity implements View.OnClickListener {
    private TextView mRegister_tv, mFrogetPW_tv;
    private Button mLogin_btn;
    private EditText mUsername_et, mVerifyCode_et;
    private boolean userName_Flag, psw_Flag;

    private String timerUnitString;//单位：秒，以及文字
    private boolean isLoginOrGetCode = false;//判断button为获取验证码还是下一步
    private boolean isBackwardOver = false;
    private boolean isFrist = true;
    private MyCountDownTimer timer;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.snore_activity_login);
        init();
        initTitleBar();
        initView();
        initHandler();
    }


    @Override
    protected void init() {
        super.init();
        timerUnitString = getResources().getString(R.string.register_get_verfity_code_again);
        timer = new MyCountDownTimer(60000, 1000);
    }

    @Override
    protected void initHandler() {
        super.initHandler();
        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch (msg.what) {
                    case ReErrorCode.ERRCODE_SUCEED:
                        MyProgressBarDialogUtil.dismiss2Msg(R.string.login_suceed);
                        postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                MobclickAgent.onProfileSignIn(mUsername_et.getText().toString());
                                jumpActivity(activity, MainActivity.class);
                            }
                        }, 1500);
                        break;
                    case ReErrorCode.ERRCODE_FAIL:
                        MyProgressBarDialogUtil.dismiss();
                        CustomToast.showToasts(context, (String) msg.obj);
                        break;
                    case ReErrorCode.ERROR_GET_VERIFY_CODE_SUCCEED:
                        MyProgressBarDialogUtil.dismiss2Msg(R.string.login_get_code_succed);
                        timer.start();
                        break;
                    case ReErrorCode.ERROR_VERIFY_BACKWARD:
                        if (isLoginOrGetCode) {
                            btnLogin();
                            isFrist = false;
                        } else {
                            isFrist = false;
                            mLogin_btn.setEnabled(false);
                            mLogin_btn.setBackground(getResources().getDrawable(R.drawable.login_button_perss));
                            mLogin_btn.setText(timerUnitString + "(" + msg.obj + ")");
                        }
                        break;
                    case  ReErrorCode.ERRCODE_NO_RETRUN_ERROR:
                        MyProgressBarDialogUtil.dismiss();
                        break;

                    default:
                        MyProgressBarDialogUtil.dismiss();
                        break;
                }
            }
        };
    }

    @Override
    protected void initTitleBar() {
        super.initTitleBar();
        MyTitlebarUtil.showTitleName(activity, R.string.login_login);

    }

    @Override
    protected void initView() {

        mRegister_tv = (TextView) findViewById(R.id.login_tx_register);
        mRegister_tv.setOnClickListener(this);
        mFrogetPW_tv = (TextView) findViewById(R.id.login_tx_forget);
        mFrogetPW_tv.setOnClickListener(this);
        mUsername_et = (EditText) findViewById(R.id.login_et_username);
        mVerifyCode_et = (EditText) findViewById(R.id.login_et_password);
        mLogin_btn = (Button) findViewById(R.id.login_btn_login);
        mLogin_btn.setOnClickListener(this);
        mVerifyCode_et.setEnabled(false);
        mLogin_btn.setEnabled(false);
        mLogin_btn.setBackground(getResources().getDrawable(R.drawable.login_button_perss));
        mUsername_et.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                String un = editable.toString();
                if (un.length() == 0 || un.length() != 11) {
                    mVerifyCode_et.setEnabled(false);
                    mLogin_btn.setBackground(getResources().getDrawable(R.drawable.login_button_perss));
                    mLogin_btn.setEnabled(false);
                } else {
                    mVerifyCode_et.setEnabled(true);
                    mLogin_btn.setBackground(getResources().getDrawable(R.drawable.login_button));
                    mLogin_btn.setEnabled(true);
                }

            }
        });
        mVerifyCode_et.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                String pw = editable.toString();
                if (pw.length() == 0 || pw.equals("")) {
                    isLoginOrGetCode = false;
                    btnGetCode();
                } else {
                    btnLogin();
                }
            }
        });
    }

    private void btnLogin() {

        isLoginOrGetCode = true;
        mLogin_btn.setText(R.string.login_login);
        mLogin_btn.setBackground(getResources().getDrawable(R.drawable.login_button));
        mLogin_btn.setEnabled(true);


    }

    private void btnGetCode() {
        if (isBackwardOver) {
            mLogin_btn.setText(R.string.register_get_verfity_code_again);
            return;
        }
        if (isFrist == true) {
            mLogin_btn.setText(R.string.register_get_verfity_code);
        }

    }

    class MyCountDownTimer extends CountDownTimer {
        public MyCountDownTimer(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
            // TODO Auto-generated constructor stub
        }

        @Override
        public void onTick(long millisUntilFinished) {
            // TODO Auto-generated method stub
            isBackwardOver = false;
            sendMsg(ReErrorCode.ERROR_VERIFY_BACKWARD, millisUntilFinished / 1000);


        }

        @Override
        public void onFinish() {
            // TODO Auto-generated method stub
            mLogin_btn.setEnabled(true);
            mLogin_btn.setText(R.string.register_get_verfity_code_again);
            mLogin_btn.setBackground(getResources().getDrawable(R.drawable.login_button));
            isBackwardOver = true;

        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {

            case R.id.login_et_username:
                break;
            case R.id.login_et_password:
                break;
            case R.id.login_btn_login:
                String phone = mUsername_et.getText().toString();
                String vderifyCode = mVerifyCode_et.getText().toString();
                if (isLoginOrGetCode) {
                    if (CheckNetwork.checkNetwork(context)) {
                        if (DataCheckUtil.isPhoneNumberValid(phone)) {
                            SnorekillerJsonUtil.LoginWithoutRegister(handler, activity, phone, vderifyCode,  "ch");
                        }
                    }
                } else {
                    if (CheckNetwork.checkNetwork(activity)) {
                        if (DataCheckUtil.isPhoneNumberValid(phone)) {
                            SnorekillerJsonUtil.GetSMSVerifyCode(handler, context, phone);
                        }
                    }
                }
                break;
            case R.id.login_tx_register:
                jumpActivityNotFinish(activity, RegisterActivity.class);
                break;
            case R.id.login_tx_forget:
                jumpActivityNotFinish(activity, ForgetPasswordActivity.class);
                break;

        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        timer.cancel();
    }
}
